package generic.net;

import java.util.LinkedList;

/**
 * ResponseManager is responsible for pairing outbound requests with their responses.
 *
 * @author Adam Scarr <scarr.adam@gmail.com>
 */
public class RequestManager {
    private LinkedList<PendingResponse> pendingRequests = new LinkedList<PendingResponse>();

    /**
     * Add a request to the request manager.
     * @param request
     */
    public synchronized PendingResponse addRequest(Request request) {
        System.out.println("[RequestManager] sent request #" + request.getID() + " ( " + request.getServiceProvider() + " : " + request.getRequestType() + " ) ");
        PendingResponse pendingRequest = new PendingResponse(request);
        pendingRequests.add(pendingRequest);
        return pendingRequest;
    }

    /**
     * Searches the pending requests for the response, if one is found
     * the thread that is sleeping waiting for the response is woken up, and the
     * response is passed back via the PendingRequest.
     * @param response
     */
    public synchronized void addResponse(Response response) {
        System.out.println("[RequestManager] received response for request #" + response.getID());
        for (PendingResponse pendingRequest: pendingRequests) {
            if (pendingRequest.getRequest().getID() == response.getID()) {
                pendingRequest.setResponse(response);
            }
        }
    }
}
